<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Model Management</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/toastr@2.1.4/build/toastr.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
        }
        .model-card {
            transition: all 0.3s ease;
        }
        .model-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .active-model {
            border-left: 5px solid #0d6efd;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active text-white" href="#">
                                <i class="bi bi-speedometer2 me-2"></i> Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="#models-section">
                                <i class="bi bi-cpu me-2"></i> LLM Models
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="#documents-section">
                                <i class="bi bi-file-earmark-text me-2"></i> Documents
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="#users-section">
                                <i class="bi bi-people me-2"></i> Users
                            </a>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Model Management</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <button class="btn btn-sm btn-outline-secondary me-2" id="refresh-models">
                            <i class="bi bi-arrow-clockwise"></i> Refresh
                        </button>
                        <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addModelModal">
                            <i class="bi bi-plus-circle"></i> Add Model
                        </button>
                    </div>
                </div>

                <!-- Stats Cards -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="card text-white bg-primary mb-3">
                            <div class="card-body">
                                <h5 class="card-title">Total Models</h5>
                                <h2 class="card-text" id="total-models">0</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card text-white bg-success mb-3">
                            <div class="card-body">
                                <h5 class="card-title">Active Models</h5>
                                <h2 class="card-text" id="active-models">0</h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card text-white bg-info mb-3">
                            <div class="card-body">
                                <h5 class="card-title">API Models</h5>
                                <h2 class="card-text" id="api-models">0</h2>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Models Table -->
                <div class="card">
                    <div class="card-header">
                        <h4>LLM Models</h4>
                    </div>
                    <div class="card-body">
                        <table id="modelsTable" class="table table-striped table-hover" style="width:100%">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Name</th>
                                    <th>Type</th>
                                    <th>Provider</th>
                                    <th>API Endpoint</th>
                                    <th>Max Tokens</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Models will be loaded via JavaScript -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- Add Model Modal -->
    <div class="modal fade" id="addModelModal" tabindex="-1" aria-labelledby="addModelModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addModelModalLabel">Add New LLM Model</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="modelForm">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="name" class="form-label">Model Name</label>
                                <input type="text" class="form-control" id="name" required>
                            </div>
                            <div class="col-md-6">
                                <label for="model_type" class="form-label">Model Type</label>
                                <select class="form-select" id="model_type" required>
                                    <option value="">Select Type</option>
                                    <option value="chat">Chat</option>
                                    <option value="completion">Completion</option>
                                    <option value="embedding">Embedding</option>
                                </select>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="provider" class="form-label">Provider</label>
                                <input type="text" class="form-control" id="provider" required>
                            </div>
                            <div class="col-md-6">
                                <label for="api_endpoint" class="form-label">API Endpoint</label>
                                <input type="url" class="form-control" id="api_endpoint" required>
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="api_key" class="form-label">API Key</label>
                                <input type="password" class="form-control" id="api_key">
                            </div>
                            <div class="col-md-6">
                                <label for="max_tokens" class="form-label">Max Tokens</label>
                                <input type="number" class="form-control" id="max_tokens" value="8192">
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="supports_functions" checked>
                                    <label class="form-check-label" for="supports_functions">Supports Functions</label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="is_active" checked>
                                    <label class="form-check-label" for="is_active">Active</label>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">Description</label>
                            <textarea class="form-control" id="description" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveModel">Save Model</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Model Modal (Same as Add, but will be populated) -->
    <div class="modal fade" id="editModelModal" tabindex="-1" aria-labelledby="editModelModalLabel" aria-hidden="true">
        <!-- Same content as addModelModal, but with different ID -->
        <!-- We'll populate this dynamically -->
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title" id="deleteModalLabel">Confirm Deletion</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete this model? This action cannot be undone.</p>
                    <input type="hidden" id="modelToDelete">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-danger" id="confirmDelete">Delete</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/toastr@2.1.4/build/toastr.min.js"></script>
    <script>
        $(document).ready(function() {
            // Initialize Toastr
            toastr.options = {
                "closeButton": true,
                "progressBar": true,
                "positionClass": "toast-top-right",
                "timeOut": "5000"
            };

            // Initialize DataTable
            const modelsTable = $('#modelsTable').DataTable({
                responsive: true,
                columns: [
                    { data: 'model_id' },
                    { data: 'name' },
                    { data: 'model_type' },
                    { data: 'provider' },
                    { data: 'api_endpoint' },
                    { data: 'max_tokens' },
                    {
                        data: 'is_active',
                        render: function(data, type, row) {
                            return data ?
                                '<span class="badge bg-success">Active</span>' :
                                '<span class="badge bg-secondary">Inactive</span>';
                        }
                    },
                    {
                        data: null,
                        render: function(data, type, row) {
                            return `
                                <div class="btn-group" role="group">
                                    <button class="btn btn-sm btn-outline-primary edit-model" data-id="${row.model_id}">
                                        <i class="bi bi-pencil"></i> Edit
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger delete-model" data-id="${row.model_id}">
                                        <i class="bi bi-trash"></i> Delete
                                    </button>
                                </div>
                            `;
                        },
                        orderable: false
                    }
                ]
            });

            // Load models
            function loadModels() {
                $.ajax({
                    url: '/api/get_all_llm_models',
                    type: 'GET',
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
                    },
                    success: function(response) {
                        modelsTable.clear().rows.add(response).draw();

                        // Update stats
                        $('#total-models').text(response.length);
                        $('#active-models').text(response.filter(m => m.is_active).length);
                        $('#api-models').text(response.filter(m => m.api_endpoint).length);
                    },
                    error: function(xhr) {
                        toastr.error('Failed to load models: ' + xhr.responseJSON?.error || 'Unknown error');
                    }
                });
            }

            // Initial load
            loadModels();

            // Refresh button
            $('#refresh-models').click(function() {
                loadModels();
                toastr.info('Models refreshed');
            });

            // Save new model
            $('#saveModel').click(function() {
                const modelData = {
                    name: $('#name').val(),
                    model_type: $('#model_type').val(),
                    provider: $('#provider').val(),
                    api_endpoint: $('#api_endpoint').val(),
                    api_key: $('#api_key').val(),
                    max_tokens: $('#max_tokens').val(),
                    supports_functions: $('#supports_functions').is(':checked'),
                    is_active: $('#is_active').is(':checked'),
                    description: $('#description').val()
                };

                // Basic validation
                if (!modelData.name || !modelData.model_type || !modelData.provider || !modelData.api_endpoint) {
                    toastr.warning('Please fill in all required fields');
                    return;
                }

                $.ajax({
                    url: '/api/llm_models',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(modelData),
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
                    },
                    success: function(response) {
                        toastr.success('Model added successfully');
                        $('#addModelModal').modal('hide');
                        $('#modelForm')[0].reset();
                        loadModels();
                    },
                    error: function(xhr) {
                        toastr.error('Failed to add model: ' + xhr.responseJSON?.error || 'Unknown error');
                    }
                });
            });

            // Edit model (we'll implement this after showing how to fetch a single model)
            $(document).on('click', '.edit-model', function() {
                const modelId = $(this).data('id');
                // Here you would fetch the model details and populate the edit modal
                // For now, we'll just show an alert
                toastr.info('Edit functionality will be implemented next');
            });

            // Delete model
            $(document).on('click', '.delete-model', function() {
                const modelId = $(this).data('id');
                $('#modelToDelete').val(modelId);
                $('#deleteModal').modal('show');
            });

            // Confirm delete
            $('#confirmDelete').click(function() {
                const modelId = $('#modelToDelete').val();

                $.ajax({
                    url: '/api/llm_models/' + modelId,
                    type: 'DELETE',
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
                    },
                    success: function(response) {
                        toastr.success('Model deleted successfully');
                        $('#deleteModal').modal('hide');
                        loadModels();
                    },
                    error: function(xhr) {
                        toastr.error('Failed to delete model: ' + xhr.responseJSON?.error || 'Unknown error');
                    }
                });
            });

            // Check authentication on page load
            checkAuth();
        });

        function checkAuth() {
            const token = localStorage.getItem('access_token');
            if (!token) {
                window.location.href = '/login';
                return;
            }

            // Verify token
            $.ajax({
                url: '/api/current_user',
                type: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(response) {
                    if (!response.is_admin) {
                        toastr.error('You do not have admin privileges');
                        setTimeout(() => {
                            window.location.href = '/';
                        }, 2000);
                    }
                },
                error: function() {
                    localStorage.removeItem('access_token');
                    window.location.href = '/login';
                }
            });
        }
    </script>
</body>
</html>